/*************************************************************************
    > File Name: character_proc.c
    > Created Time: Wed 06 Jan 2021 06:36:28 PM PST
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>

#define FILE_NAME  "/dev/character_device"
char writebuf[] = "112233445566";
int fd;
int status;

void Proc_exit_info(int status)
{
	if(WIFEXITED(status))
	{
		printf("Normal terminate,exit status:%d\n",WEXITSTATUS(status));
	}
	else if(WIFSIGNALED(status))
	{
		printf("Abnormal terminate,signal number:%d\n",WTERMSIG(status));
	}
	else
	{
		printf("other status\n");
	}
	
}

int main(int argc,char *argv[])
{
	pid_t pid;
	int ret;
	char readbuf[200]={};

	fd = open(FILE_NAME,O_RDWR);/*O_RDWR 阻塞读写*/
	if(fd < 0)
	{
	    printf("Can't open file %s\r\n",FILE_NAME);
	}

	printf("Run here,opened %s fd:%d\r\n",FILE_NAME,fd);

	pid = fork();/*创建进程*/
	if(pid == 0)/*子进程PID返回0*/
	{
		printf("Here is child,my pid = %d,parent's pid = %d\r\n",getpid(),getppid());
		ret = read(fd,readbuf,50);
		if(ret < 0)
		{
			printf("chaild proc read Failed:%d\n",fd);
		}
		else
		{
		    printf("chaild proc read len:%ld data:%s\n",strlen(readbuf),readbuf);
		}
		printf("Child proc Run Exit\r\n");
		exit(3);
	}
	else if(pid > 0)/*父进程返回子进程PID*/
	{
		printf("Here is parent,my pid = %d,child's pid = %d\n",getpid(),pid);
        sleep(3);
		printf("Parent proc write:%s\n",writebuf);
		ret = write(fd,writebuf,strlen(writebuf));
		if(ret < 0)
		{
			printf("parent proc write failed\r\n");
		}
		sleep(3);
		wait(&status);
		Proc_exit_info(status);
		printf("Parent Proc read Child exit status:%d\n",status);
	}
	else
	{
	    perror("fork Error\n");
	}
	
	ret = close(fd);
	if(ret < 0 )
	{
		printf("can't close file %s\n",FILE_NAME);
	}
	else
	{
		printf("%s close success!\r\n",FILE_NAME);
	}
	
    return 0;
}



